package com.sdjzu.wanfuying.androiddesign.mvvm.student;

import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;

import com.sdjzu.wanfuying.androiddesign.BR;
import com.sdjzu.wanfuying.androiddesign.R;
import com.sdjzu.wanfuying.androiddesign.base.BaseActivity;

import java.util.ArrayList;
import java.util.List;

import androidx.annotation.NonNull;
import androidx.databinding.DataBindingUtil;
import androidx.databinding.ViewDataBinding;
import androidx.viewpager.widget.PagerAdapter;
import androidx.viewpager.widget.ViewPager;
import butterknife.BindView;

public class StudentViewPagerActivity extends BaseActivity {
    @BindView(R.id.activity_student_view_pager_viewpager)
    ViewPager mViewPager;
    private StudentViewPagerAdapter adapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_student_view_pager);

        mViewPager.setAdapter(adapter = new StudentViewPagerAdapter());
    }

    class StudentViewPagerAdapter extends PagerAdapter {
        private final static int STUDENT_NUM = 10;
        private List<Student> studentList = new ArrayList<>(STUDENT_NUM);

        public StudentViewPagerAdapter() {
            studentList.clear();
            for (int i = 0; i < STUDENT_NUM; i++) {
                Student student = new Student("2014000" + i, Math.random() + "");
                student.setAvatarUrl("https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1548663767481&di=273eafa024cfdbcb29764b0dfaa66fde&imgtype=0&src=http%3A%2F%2Fpic23.nipic.com%2F20120904%2F6772262_115609168000_2.jpg");
                studentList.add(student);
            }
        }

        public void refresh() {
            for (Student student : studentList) {
                student.setName(Math.random() + "");
            }
        }

        @Override
        public int getCount() {
            return studentList.size();
        }

        @Override
        public boolean isViewFromObject(@NonNull View view, @NonNull Object object) {
            return view == ((ViewDataBinding) object).getRoot();
        }

        @NonNull
        @Override
        public Object instantiateItem(@NonNull ViewGroup container, int position) {
            ViewDataBinding viewDataBinding = DataBindingUtil.inflate(getLayoutInflater(), R.layout.activity_student_view_pager_item, container, true);
            viewDataBinding.setVariable(BR.student, studentList.get(position));
            return viewDataBinding;
        }

        @Override
        public void destroyItem(@NonNull ViewGroup container, int position, @NonNull Object object) {
            container.removeView(((ViewDataBinding) object).getRoot());
        }
    }
}
